<template>
  <div class="home">
    <!-- 导航栏 -->
    <el-menu
      :default-active="activeIndex"
      class="nav-menu"
      mode="horizontal"
      @select="handleSelect"
      background-color="rgba(255, 255, 255, 0.95)"
      text-color="#2c3e50"
      active-text-color="#667eea">
      <el-menu-item index="1">
        <el-icon><Reading /></el-icon>
        <span>新书上架</span>
      </el-menu-item>
      <el-menu-item index="2">
        <el-icon><Collection /></el-icon>
        <span>全部图书</span>
      </el-menu-item>
      <el-menu-item index="3">
        <el-icon><DocumentChecked /></el-icon>
        <span>已被借阅</span>
      </el-menu-item>
      <!-- 普通用户专属导航：我的借阅/借阅历史 -->
      <el-menu-item index="4" v-if="!isAdmin && userInfo.userName">
        <el-icon><User /></el-icon>
        <span>我的借阅</span>
      </el-menu-item>
      <el-menu-item index="5" v-if="!isAdmin && userInfo.userName">
        <el-icon><Clock /></el-icon>
        <span>借阅历史</span>
      </el-menu-item>
      <!-- 管理员专属导航：用户中心 -->
      <el-menu-item v-if="isAdmin" index="6">
        <el-icon><User /></el-icon>
        <span>用户中心</span>
      </el-menu-item>

      <!-- 搜索框 -->
      <div class="nav-search">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索图书名称、作者或ISBN"
          class="nav-search-input"
          @keyup.enter="handleSearch">
          <template v-slot:prefix>
            <el-icon class="search-prefix-icon">
              <SearchIcon />
            </el-icon>
          </template>
          <template v-slot:append>
            <el-button @click="handleSearch">
              <el-icon><SearchIcon /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>

      <div class="user-menu">
        <el-dropdown @command="handleCommand">
          <span class="el-dropdown-link">
            <!-- 新增：圆形头像显示 -->
            <div class="avatar-container">
              <img 
                :src="avatarUrl || defaultAvatarUrl" 
                alt="用户头像" 
                class="avatar-image"
              >
            </div>
            {{ userInfo.userName || '我的' }} <el-icon><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <!-- 修复：添加userInfo存在的兜底判断，避免空值导致菜单不渲染 -->
              <el-dropdown-item command="profile" v-if="userInfo && userInfo.userName">个人信息</el-dropdown-item>
              <el-dropdown-item command="logout" divided>登出</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-menu>


    <!-- 内容区域 -->
    <div class="content-container" :class="{ 'carousel-mode': activeIndex === '1' }">
      <!-- 新书上架：关键优化1：传递isAdmin属性 -->
      <div v-if="activeIndex === '1'" class="carousel-section">
        <Book3DCarousel
          :books="latestBooks"
          :auto-play="true"
          :interval="3000"
          :is-admin="isAdmin"
          @borrow-book="borrowBook"
        />
      </div>

      <!-- 全部图书 -->
      <div v-if="activeIndex === '2'" class="section">
        <div class="section-title">
          <el-icon><Collection /></el-icon>
          <h2>全部图书</h2>
        </div>

        <!-- 搜索和排序工具栏 -->
        <div class="toolbar">
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索图书名称、作者或ISBN"
              style="width: 300px"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">搜索</el-button>
              </template>
            </el-input>
          </div>

          <!-- 管理员专属工具栏：排序+增删改按钮 -->
          <div v-if="isAdmin" class="admin-box">
            <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort" class="sort-select">
              <el-option label="按上架时间（升序）" value="uploadtime_asc"></el-option>
              <el-option label="按上架时间（降序）" value="uploadtime_desc"></el-option>
              <el-option label="按书名（升序）" value="bookname_asc"></el-option>
              <el-option label="按书名（降序）" value="bookname_desc"></el-option>
              <el-option label="按作者（升序）" value="author_asc"></el-option>
              <el-option label="按作者（降序）" value="author_desc"></el-option>
              <el-option label="按价格（升序）" value="price_asc"></el-option>
              <el-option label="按价格（降序）" value="price_desc"></el-option>
            </el-select>
            <el-button type="primary" @click="showAddBookDialog">
              <el-icon><Plus /></el-icon>
              发布新书
            </el-button>
            <el-button type="success" @click="showEditBookDialog" :disabled="!selectedBook">
              <el-icon><Edit /></el-icon>
              编辑图书
            </el-button>
            <el-button type="danger" @click="showDeleteBookDialog" :disabled="!selectedBook">
              <el-icon><Delete /></el-icon>
              删除图书
            </el-button>
          </div>
        </div>

        <!-- 搜索结果卡片视图 -->
        <div v-if="showSearchResults" class="search-results">
          <h3>搜索结果 ({{ searchResults.length }} 本)</h3>
          <div class="book-cards">
            <div v-for="book in searchResults" :key="book.bookId" class="book-card">
              <div class="book-image">
                <img v-if="getBookImage(book)" :src="getBookImage(book)" :alt="book.bookName" :data-isbn="book.bookIsbn" @error="handleImageError">
                <div v-else class="book-cover-placeholder">
                  <div class="book-cover-icon">{{ getBookIcon(book) }}</div>
                  <div class="book-cover-title">{{ book.bookName }}</div>
                  <div class="book-cover-author">{{ book.bookAuthor }}</div>
                  <div class="book-cover-category">{{ getBookCategory(book) }}</div>
                </div>
              </div>
              <div class="book-info">
                <h4 class="book-title">{{ book.bookName }}</h4>
                <p class="book-author">作者：{{ book.bookAuthor }}</p>
                <p class="book-isbn">ISBN：{{ book.bookIsbn }}</p>
                <p class="book-press">出版社：{{ book.bookPress }}</p>
                <p class="book-price">价格：¥{{book.bookPrice }}</p>
                <p class="book-status">
                  <el-tag :type="getStatusType(book.bookStatus)">
                    {{ getStatusText(book.bookStatus) }}
                  </el-tag>
                </p>
                <div class="book-actions">
                  <!-- 普通用户专属：借阅按钮 -->
                  <el-button
                    type="primary"
                    @click="borrowBook(book)"
                    :disabled="book.bookStatus !== '0'"
                    v-if="!isAdmin && userInfo.userName">
                    {{ book.bookStatus === '0' ? '借阅' : '不可借阅' }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 图书表格 -->
        <el-table :data="paginatedBooks" style="width: 100%" @selection-change="handleSelectionChange" ref="bookTable">
          <!-- 管理员专属：选择框 -->
          <el-table-column v-if="isAdmin" type="selection" width="55">
          </el-table-column>
          <el-table-column prop="bookName" label="图书名称" width="200">
            <template #default="{ row }">
              <span>{{ row.bookName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="bookAuthor" label="作者" width="150">
            <template #default="{ row }">
              <span>{{ row.bookAuthor }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="bookIsbn" label="ISBN" width="150">
            <template #default="{ row }">
              <span>{{ row.bookIsbn }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="bookPress" label="出版社" width="150">
            <template #default="{ row }">
              <span>{{ row.bookPress }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="bookPrice" label="价格" width="100">
            <template #default="{ row }">
              <span>¥{{ row.bookPrice }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="bookUploadtime" label="上架时间" width="150">
            <template #default="{ row }">
              <span>{{ formatDate(row.bookUploadtime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="bookStatus" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.bookStatus)">
                {{ getStatusText(row.bookStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="{ row }">
              <!-- 普通用户专属：借阅按钮 -->
              <el-button
                type="primary"
                size="small"
                @click="borrowBook(row)"
                :disabled="row.bookStatus !== '0'"
                v-if="!isAdmin && userInfo.userName">
                {{ row.bookStatus === '0' ? '借阅' : '已借阅' }}
              </el-button>
              <!-- 公共功能：详情按钮 -->
              <el-button
                type="info"
                size="small"
                @click="showBookDetail(row)">
                详情
              </el-button>
              <!-- 管理员专属：编辑/删除按钮 -->
              <el-button
                type="success"
                size="small"
                @click="showEditBookDialog(row)"
                :disabled="row.bookStatus !== '0'"
                v-if="isAdmin">
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="showDeleteBookDialog(row)"
                :disabled="row.bookStatus !== '0'"
                v-if="isAdmin">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="filteredBooks.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 已被借阅：管理员可查看详情，普通用户仅查看列表 -->
      <div v-if="activeIndex === '3'" class="section">
        <div class="section-title">
          <el-icon><DocumentChecked /></el-icon>
          <h2>已被借阅</h2>
        </div>
        <el-table :data="paginatedBorrowedBooks" style="width: 100%">
          <el-table-column prop="bookName" label="图书名称" width="200"></el-table-column>
          <el-table-column prop="bookAuthor" label="作者" width="150"></el-table-column>
          <el-table-column prop="bookIsbn" label="ISBN" width="150"></el-table-column>
          <!-- 管理员专属：借阅人信息 -->
          <el-table-column label="借阅人" width="100" v-if="isAdmin">
            <template #default="{ row }">
              <span>{{ row.bookBorrower || '未知' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="bookBorrowtime" label="借阅时间" width="150"></el-table-column>
          <el-table-column prop="bookReturntime" label="预计归还时间" width="150"></el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="borrowedCurrentPage"
            v-model:page-size="borrowedPageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="borrowedBooks.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleBorrowedSizeChange"
            @current-change="handleBorrowedCurrentChange"
          />
        </div>
      </div>

      <!-- 我的借阅：普通用户专属 -->
      <div v-if="activeIndex === '4' && !isAdmin && userInfo.userName" class="section">
        <div class="section-title">
          <el-icon><User /></el-icon>
          <h2>我的借阅</h2>
        </div>
        <el-table :data="paginatedMyRecords" style="width: 100%">
          <el-table-column prop="bookName" label="图书名称" width="200"></el-table-column>
          <el-table-column prop="bookIsbn" label="ISBN" width="150"></el-table-column>
          <el-table-column prop="bookBorrowtime" label="借阅时间" width="150"></el-table-column>
          <el-table-column prop="bookReturntime" label="预计归还时间" width="150"></el-table-column>
          <el-table-column prop="bookStatus" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getMyRecordStatusType(row.bookStatus)">
                {{ getMyRecordStatusText(row.bookStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
             <el-button
              type="success"
              size="small"
              @click="returnBook(row)"
              :disabled="row.bookStatus !== '1'">
              {{ row.bookStatus === '1' ? '归还' : '已归还' }}
            </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="myRecordsCurrentPage"
            v-model:page-size="myRecordsPageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="myRecords.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleMyRecordsSizeChange"
            @current-change="handleMyRecordsCurrentChange"
          />
        </div>
      </div>

      <!-- 借阅历史：普通用户专属 -->
      <div v-if="activeIndex === '5' && !isAdmin && userInfo.userName" class="section">
        <div class="section-title">
          <el-icon><Clock /></el-icon>
          <h2>借阅历史</h2>
        </div>
        <div class="history-info">
          <p>显示您所有的借阅记录，包括已归还的图书</p>
        </div>
        <el-table :data="paginatedBorrowHistoryRecords" style="width: 100%" :empty-text="'暂无借阅记录'">
          <el-table-column prop="recordBookname" label="图书名称" width="180">
            <template #default="{ row }">
              <span class="book-name">{{ row.recordBookname }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="recordBookisbn" label="ISBN" width="140">
            <template #default="{ row }">
              <span class="book-isbn">{{ row.recordBookisbn }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="recordBorrowtime" label="借阅时间" width="140">
            <template #default="{ row }">
              <span>{{ formatDate(row.recordBorrowtime) }}</span>
            </template>
          </el-table-column>
          <!-- 借阅历史表格新增“预计归还时间”列 -->
          <el-table-column prop="bookReturntime" label="预计归还时间" width="140">
            <template #default="{ row }">
              <span>{{ row.bookReturntime || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="recordRemandtime" label="实际归还时间" width="140">
            <template #default="{ row }">
              <span>{{ row.recordRemandtime ? formatDate(row.recordRemandtime) : '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="80">
            <template #default="{ row }">
              <el-tag type="success">已归还</el-tag>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="historyCurrentPage"
            v-model:page-size="historyPageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="borrowHistoryRecords.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleHistorySizeChange"
            @current-change="handleHistoryCurrentChange"
          />
        </div>
      </div>

      <!-- 用户中心：管理员专属 -->
      <div v-if="activeIndex === '6' && isAdmin" class="section">
        <div class="section-title">
          <el-icon><User /></el-icon>
          <h2>用户管理中心</h2>
        </div>

        <div class="user-center-content">
          <el-alert
            title="管理员功能"
            type="info"
            :closable="false"
            show-icon>
            <template #default>
              <p>您正在访问用户管理中心，可以管理所有用户信息和重置密码。</p>
              <p>点击下方按钮进入完整的用户管理界面。</p>
            </template>
          </el-alert>

          <div class="user-center-actions">
            <el-button type="primary" size="large" @click="goToUserCenter">
              <el-icon><User /></el-icon>
              进入用户中心
            </el-button>
            <el-button type="success" size="large" @click="refreshUserData">
              <el-icon><Refresh /></el-icon>
              刷新用户数据
            </el-button>
          </div>

          <div class="user-stats">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-icon">
                      <el-icon><User /></el-icon>
                    </div>
                    <div class="stat-info">
                      <div class="stat-number">{{ userStats.totalUsers }}</div>
                      <div class="stat-label">总用户数</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-icon admin">
                      <el-icon><User /></el-icon>
                    </div>
                    <div class="stat-info">
                      <div class="stat-number">{{ userStats.adminUsers }}</div>
                      <div class="stat-label">管理员</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card class="stat-card">
                  <div class="stat-content">
                    <div class="stat-icon normal">
                      <el-icon><User /></el-icon>
                    </div>
                    <div class="stat-info">
                      <div class="stat-number">{{ userStats.normalUsers }}</div>
                      <div class="stat-label">普通用户</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>

    </div>


    <!-- 发布新书对话框：管理员专属 -->
    <el-dialog title="发布新书" v-model="addBookDialogVisible" width="600px" v-if="isAdmin">
      <el-form :model="bookForm" label-width="100px" :rules="bookFormRules" ref="addBookForm">
        <el-form-item label="图书名称" prop="bookName">
          <el-input v-model="bookForm.bookName" placeholder="请输入图书名称"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="bookAuthor">
          <el-input v-model="bookForm.bookAuthor" placeholder="请输入作者"></el-input>
        </el-form-item>
        <el-form-item label="ISBN" prop="bookIsbn">
          <el-input v-model="bookForm.bookIsbn" placeholder="请输入ISBN"></el-input>
        </el-form-item>
        <el-form-item label="出版社">
          <el-input v-model="bookForm.bookPress" placeholder="请输入出版社"></el-input>
        </el-form-item>
        <el-form-item label="页数">
          <el-input v-model="bookForm.bookPagination" placeholder="请输入页数" type="number"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="bookForm.bookPrice" placeholder="请输入价格" type="number"></el-input>
        </el-form-item>
        <el-form-item label="图书封面">
          <el-upload
            class="book-uploader"
            :show-file-list="false"
            :before-upload="handleImageUpload"
            :on-change="handleImageUpload"
            accept="image/*"
            :auto-upload="false">
            <img v-if="bookForm.bookImage" :src="bookForm.bookImage" class="book-image-preview">
            <el-icon v-else class="book-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            <p>点击上传图书封面（可选）</p>
            <p>支持 JPG、PNG 格式，大小不超过 2MB</p>
          </div>
          <div v-if="bookForm.bookImage" class="image-actions">
            <el-button size="small" type="danger" @click="removeImage">删除图片</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addBookDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddBook">发布</el-button>
      </template>
    </el-dialog>

    <!-- 编辑图书对话框：管理员专属 -->
    <el-dialog title="编辑图书" v-model="editBookDialogVisible" width="600px" v-if="isAdmin">
      <el-form :model="bookForm" label-width="100px" :rules="bookFormRules" ref="editBookForm">
        <el-form-item label="图书名称" prop="bookName">
          <el-input v-model="bookForm.bookName" placeholder="请输入图书名称"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="bookAuthor">
          <el-input v-model="bookForm.bookAuthor" placeholder="请输入作者"></el-input>
        </el-form-item>
        <el-form-item label="ISBN" prop="bookIsbn">
          <el-input v-model="bookForm.bookIsbn" placeholder="请输入ISBN"></el-input>
        </el-form-item>
        <el-form-item label="出版社">
          <el-input v-model="bookForm.bookPress" placeholder="请输入出版社"></el-input>
        </el-form-item>
        <el-form-item label="页数">
          <el-input v-model="bookForm.bookPagination" placeholder="请输入页数" type="number"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="bookForm.bookPrice" placeholder="请输入价格" type="number"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editBookDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditBook">保存</el-button>
      </template>
    </el-dialog>

    <!-- 删除图书确认对话框：管理员专属 -->
    <el-dialog title="删除图书" v-model="deleteBookDialogVisible" width="400px" v-if="isAdmin">
      <p>确定要删除图书《{{ selectedBook ? selectedBook.bookName : '' }}》吗？</p>
      <p style="color: #f56c6c; font-size: 14px;">注意：此操作不可撤销，且只能删除未被借阅的图书。</p>
      <template #footer>
        <el-button @click="deleteBookDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleDeleteBook">确定删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { Reading, Collection, DocumentChecked, User, Clock, Search as SearchIcon, ArrowDown, Plus, Edit, Delete, Refresh } from '@element-plus/icons-vue'
// HomeView.vue 中导入接口的部分
import { 
  addBook, updateBook, deleteBook, getAllBooks, 
  getMyBorrowedBooks, getMyRecords, getAllRecords,
  borrowBook as borrowBookApi, // 重命名为 borrowBookApi
  returnBook 
} from '@/api/book'

import { getAllUsers, getCurrentUser } from '@/api/user' // 关键优化2：导入用户信息接口
import { nextTick, onMounted } from 'vue'
import Book3DCarousel from '@/components/Book3DCarousel.vue'

export default {
  name: 'HomeView',
  components: {
    Book3DCarousel,
    Reading,
    Collection,
    DocumentChecked,
    User,
    Clock,
    SearchIcon,
    ArrowDown,
    Plus,
    Edit,
    Delete,
    Refresh
  },
  data() {
    return {
      activeIndex: '1',
      searchKeyword: '',
      searchResults: [],
      showSearchResults: false,
      latestBooks: [],
      allBooks: [],
      borrowedBooks: [],
      myRecords: [],
      borrowHistoryRecords: [],
      sortBy: 'uploadtime_desc',
      currentPage: 1,
      pageSize: 10,
      filteredBooks: [],
      isMounted: false,
      borrowedCurrentPage: 1,
      borrowedPageSize: 10,
      myRecordsCurrentPage: 1,
      myRecordsPageSize: 10,
      historyCurrentPage: 1,
      historyPageSize: 10,
      // 核心权限标识
      isAdmin: false,
      addBookDialogVisible: false,
      editBookDialogVisible: false,
      deleteBookDialogVisible: false,
      selectedBook: null,
      selectedBooks: [],
      bookForm: {
        bookName: '',
        bookAuthor: '',
        bookIsbn: '',
        bookPress: '',
        bookPagination: '',
        bookPrice: '',
        bookImage: ''
      },
      bookFormRules: {
        bookName: [
          { required: true, message: '请输入图书名称', trigger: 'blur' }
        ],
        bookAuthor: [
          { required: true, message: '请输入作者', trigger: 'blur' }
        ],
        bookIsbn: [
          { required: true, message: '请输入ISBN', trigger: 'blur' }
        ]
      },
      userStats: {
        totalUsers: 0,
        adminUsers: 0,
        normalUsers: 0
      },
      userInfo: {
        userName: '',
        userEmail: '',
        userRole: '',
        userStatus: ''
      },
      // 新增：头像相关
      avatarUrl: '',
      defaultAvatarUrl: 'https://p11-doubao-search-sign.byteimg.com/labis/556e6ce4457c87dadf77e6edb7c34a3a~tplv-be4g95zd3a-image.jpeg?rk3s=542c0f93&x-expires=1777338993&x-signature=jrwvnPNL41yHsULnoMQLmU9IEMc%3D'
    }
  },
  computed: {
    paginatedBooks() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredBooks.slice(start, end);
    },
    paginatedBorrowedBooks() {
      const start = (this.borrowedCurrentPage - 1) * this.borrowedPageSize;
      const end = start + this.borrowedPageSize;
      return this.borrowedBooks.slice(start, end);
    },
    paginatedMyRecords() {
      const start = (this.myRecordsCurrentPage - 1) * this.myRecordsPageSize;
      const end = start + this.myRecordsPageSize;
      return this.myRecords.slice(start, end);
    },
    paginatedBorrowHistoryRecords() {
      const start = (this.historyCurrentPage - 1) * this.historyPageSize;
      const end = start + this.historyPageSize;
      return this.borrowHistoryRecords.slice(start, end);
    }
  },
  mounted() {
    this.isMounted = true;
    // 关键优化3：优先调用后端接口获取最新用户信息
    this.loadUserInfoFromApi().then(() => {
      this.checkAdminRole();
      this.loadAllBooks();
      this.updateBodyScroll();
      // 新增：加载用户头像
      this.loadUserAvatar();
    });
  },
  beforeUnmount() {
    this.isMounted = false;
    document.body.style.overflow = '';
  },
  watch: {
    activeIndex() {
      this.updateBodyScroll();
    },
    // 监听用户信息变化，实时更新权限
    userInfo: {
      handler() {
        this.checkAdminRole();
      },
      deep: true
    }
  },
  methods: {
    updateBodyScroll() {
      // 仅当显示轮播图（activeIndex=1）时隐藏body滚动，其他场景允许滚动
      if (this.activeIndex === '1') {
        document.body.style.overflow = 'hidden';
      } else {
        document.body.style.overflow = ''; // 其他场景恢复滚动
      }
    },

    handleSelect(key) {
      if (!this.isMounted) return;
      
      // 管理员权限拦截：禁止访问借阅相关模块
      if (this.isAdmin && (key === '4' || key === '5')) {
        this.activeIndex = '2';
        ElMessage.warning('管理员无借阅权限，已为您跳转至全部图书');
      } 
      // 普通用户未登录拦截：禁止访问个人模块
      else if (!this.isAdmin && !this.userInfo.userName && (key === '4' || key === '5')) {
        this.activeIndex = '2';
        ElMessage.warning('请先登录后查看个人借阅信息');
      } 
      // 正常切换
      else {
        this.activeIndex = key;
      }

      this.currentPage = 1;
      this.showSearchResults = false;
      this.searchResults = [];
      this.loadData();
    },

    loadData() {
      switch (this.activeIndex) {
        case '1':
          this.latestBooks = this.allBooks.slice(0, 5);
          break;
        case '2':
          this.loadAllBooks();
          break;
        case '3':
          this.borrowedBooks = this.allBooks.filter(book => book.bookStatus === '1');
          break;
        case '4':
          // 仅登录普通用户加载我的借阅
          if (!this.isAdmin && this.userInfo.userName) {
            this.loadMyRecords();
          } else {
            this.myRecords = [];
          }
          break;
        case '5':
          // 仅登录普通用户加载借阅历史
          if (!this.isAdmin && this.userInfo.userName) {
            this.loadBorrowHistory();
          } else {
            this.borrowHistoryRecords = [];
          }
          break;
        case '6':
        // 仅管理员加载用户统计，非管理员直接清空数据
        if (this.isAdmin) {
          this.loadUserStats();
        } else {
          this.userStats = { totalUsers: 0, adminUsers: 0, normalUsers: 0 };
          // 非管理员访问时，强制跳转并提示
          this.activeIndex = '2';
          ElMessage.warning('无权限访问用户中心，仅管理员可操作');
        }
        break;
      }
    },

    async loadUserInfoFromApi() {
      return new Promise(async (resolve) => {
        try {
          const response = await getCurrentUser();
          
          // 精准适配：按code=0取data中的用户信息
          if (response.code === 0 && response.data) {
            this.userInfo = response.data;
            localStorage.setItem('userInfo', JSON.stringify(response.data));
          } else {
            const localUser = localStorage.getItem('userInfo');
            if (localUser) {
              this.userInfo = JSON.parse(localUser);
            }
          }
        } catch (error) {
          console.error('加载用户信息失败:', error);
          const localUser = localStorage.getItem('userInfo');
          if (localUser) {
            this.userInfo = JSON.parse(localUser);
          }
        } finally {
          resolve();
        }
      });
    },

    // 新增：加载用户头像
    async loadUserAvatar() {
      try {
        // 从本地存储获取头像URL
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
        if (userInfo.avatarUrl) {
          this.avatarUrl = userInfo.avatarUrl;
          return;
        }
        
        // 从用户信息中获取头像URL
        if (this.userInfo && this.userInfo.avatarUrl) {
          this.avatarUrl = this.userInfo.avatarUrl;
          // 更新本地存储
          localStorage.setItem('userInfo', JSON.stringify({
            ...userInfo,
            avatarUrl: this.avatarUrl
          }));
        } else {
          this.avatarUrl = '';
        }
      } catch (error) {
        console.error('获取用户头像失败:', error);
        this.avatarUrl = '';
      }
    },

    checkAdminRole() {
      // 双重校验：用户信息存在 + 角色为ADMIN（兼容大小写）
      this.isAdmin = this.userInfo?.userRole 
        ? this.userInfo.userRole.toUpperCase() === 'ADMIN' 
        : false;
    },

    async loadAllBooks() {
      try {
        const response = await getAllBooks();
        
        // 精准适配后端：按code=0判断成功，取response.data作为图书列表
        if (response.code === 0) {
          this.allBooks = Array.isArray(response.data) ? response.data : [];
          nextTick(() => {
            if (this.isMounted) {
              this.applyFiltersAndSort();
              this.borrowedBooks = this.allBooks.filter(book => book.bookStatus === '1');
              if (this.activeIndex === '1') {
                this.latestBooks = this.allBooks.slice(0, 5);
              }
            }
          });
        } else {
          ElMessage.error(response.message || '获取图书列表失败');
          this.allBooks = [];
          this.filteredBooks = [];
        }
      } catch (error) {
        console.error('获取图书失败:', error);
        ElMessage.error('网络异常，获取图书失败');
        this.allBooks = [];
        this.filteredBooks = [];
      }
    },

    async loadMyRecords() {
      // 前置校验：普通用户 + 已登录
      if (this.isAdmin || !this.userInfo.userName) {
        this.myRecords = [];
        return;
      }

      try {
        const response = await getMyBorrowedBooks();
        if (this.isMounted) {
          this.myRecords = response.data || [];
        }
      } catch (error) {
        console.error('获取我的借阅记录失败:', error);
        if (this.isMounted) {
          ElMessage.error('获取我的借阅记录失败');
          this.myRecords = [];
        }
      }
    },

   async loadBorrowHistory() {
      // 前置校验：普通用户 + 已登录
      if (this.isAdmin || !this.userInfo.userName) {
        this.borrowHistoryRecords = [];
        return;
      }

      try {
        // 调用普通用户专属的历史借阅接口
        const response = await getMyRecords();
        if (this.isMounted) {
          this.borrowHistoryRecords = response.data || [];
        }
      } catch (error) {
        // 打印详细错误信息，便于排查
        console.error('获取借阅历史失败详情:', {
          status: error.response?.status,
          data: error.response?.data,
          message: error.message
        });
        if (this.isMounted) {
          // 显示后端返回的错误信息，更精准
          const errorMsg = error.response?.data?.message || '请求失败，请稍后重试';
          ElMessage.error(`获取借阅历史失败：${errorMsg}`);
          this.borrowHistoryRecords = [];
        }
      }
    },

    handleSearch() {
      if (!this.searchKeyword.trim()) {
        ElMessage.warning('请输入搜索关键词');
        return;
      }

      const keyword = this.searchKeyword.toLowerCase();
      this.searchResults = this.allBooks.filter(book =>
        book && (
          (book.bookName && book.bookName.toLowerCase().includes(keyword)) ||
          (book.bookAuthor && book.bookAuthor.toLowerCase().includes(keyword)) ||
          (book.bookIsbn && book.bookIsbn.toLowerCase().includes(keyword))
        )
      );
      this.showSearchResults = true;
      this.activeIndex = '2';
      ElMessage.success(`找到 ${this.searchResults.length} 本相关图书`);
    },

    async borrowBook(book) {
      // 新增：参数合法性兜底
      if (!book || typeof book.bookId === 'undefined') {
        ElMessage.error('图书信息异常，无法借阅');
        return;
      }

      // 权限拦截：管理员禁止借阅
      if (this.isAdmin) {
        ElMessage.error('管理员无借阅权限');
        return;
      }
      // 登录拦截：未登录禁止借阅
      if (!this.userInfo.userName) {
        ElMessage.warning('请先登录后借阅图书');
        return;
      }
      // 状态拦截：不可借阅状态禁止操作
      if (book.bookStatus !== '0') {
        ElMessage.warning('当前图书不可借阅');
        return;
      }

      ElMessageBox.confirm(
        `确定要借阅《${book.bookName}》吗？`,
        '借阅确认',
        {
          confirmButtonText: '确认借阅',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).then(async () => {
        try {
          // 验证参数并调用接口
          console.log('借阅图书ID:', book.bookId, '类型:', typeof book.bookId);
          const response = await borrowBookApi(book.bookId);
          if (response.code === 0) {
            ElMessage.success('借阅成功');
            this.loadData();
          } else {
            ElMessage.error('借阅失败：' + (response.message || '未知错误'));
          }
        } catch (error) {
          console.error('借阅失败:', error);
          ElMessage.error('借阅失败');
        }
      }).catch(() => {
        ElMessage.info('已取消借阅');
      });
    },

    
        // 普通用户专属：归还功能（修复后）
    async returnBook(record) {
      if (this.isAdmin) {
        ElMessage.error('管理员无归还权限');
        return;
      }
      if (!this.userInfo.userName) {
        ElMessage.warning('请先登录后归还图书');
        return;
      }
      if (record.bookStatus !== '1') {
        ElMessage.warning('当前图书无需归还');
        return;
      }

      ElMessageBox.confirm(
        `确定要归还《${record.bookName}》吗？`,
        '归还确认',
        { confirmButtonText: '确认归还', cancelButtonText: '取消', type: 'info' }
      ).then(async () => {
        try {
          const response = await returnBook(record.bookId);
          
          // 精准适配后端：按code=0判断成功
          if (response.code === 0) {
            ElMessage.success(response.message || '归还成功');
            if (this.activeIndex === '4') {
              this.loadMyRecords();
            }
            this.loadData();
          } else {
            ElMessage.error(response.message || '归还失败');
          }
        } catch (error) {
          console.error('归还失败:', error);
          ElMessage.error('网络异常，归还失败');
        }
      }).catch(() => {
        ElMessage.info('已取消归还');
      });
    },

    handleCommand(command) {
      console.log('触发dropdown命令:', command);
      if (command === 'profile') {
        // 关键修改：删除弹窗逻辑，改为路由跳转
        this.$router.push('/profile'); // 跳转至个人信息页面，路由路径需与路由配置一致
        console.log('跳转至个人信息页面');
      } else if (command === 'logout') {
        this.logout(); // 保留原登出逻辑
      }
    },

    applyFiltersAndSort() {
      nextTick(() => {
        try {
          if (!this.isMounted || !Array.isArray(this.allBooks)) {
            this.filteredBooks = [];
            return;
          }

          let data = [...this.allBooks];
          // 搜索过滤
          if (this.searchKeyword.trim()) {
            const keyword = this.searchKeyword.toLowerCase();
            data = data.filter(book =>
              book && (
                (book.bookName && book.bookName.toLowerCase().includes(keyword)) ||
                (book.bookAuthor && book.bookAuthor.toLowerCase().includes(keyword)) ||
                (book.bookIsbn && book.bookIsbn.toLowerCase().includes(keyword))
              )
            );
          }
          // 排序处理
          if (this.sortBy) {
            const [field, order] = this.sortBy.split('_');
            data.sort((a, b) => {
              let aVal = a[field === 'bookname' ? 'bookName' : field === 'author' ? 'bookAuthor' : `book${field.charAt(0).toUpperCase() + field.slice(1)}`] || '';
              let bVal = b[field === 'bookname' ? 'bookName' : field === 'author' ? 'bookAuthor' : `book${field.charAt(0).toUpperCase() + field.slice(1)}`] || '';
              if (field === 'uploadtime') {
                aVal = new Date(aVal);
                bVal = new Date(bVal);
              } else if (field === 'price') {
                aVal = parseFloat(aVal) || 0;
                bVal = parseFloat(bVal) || 0;
              }
              return order === 'asc' ? (aVal > bVal ? 1 : -1) : (aVal < bVal ? 1 : -1);
            });
          }

          this.filteredBooks = data;
          this.currentPage = 1;
        } catch (error) {
          console.error('过滤排序出错:', error);
          this.filteredBooks = [];
          this.currentPage = 1;
        }
      });
    },

    handleSort() {
      this.applyFiltersAndSort();
    },

    handleSizeChange(val) {
      if (this.isMounted) {
        this.pageSize = val;
        this.currentPage = 1;
      }
    },

    handleCurrentChange(val) {
      if (this.isMounted) {
        this.currentPage = val;
      }
    },

    handleBorrowedSizeChange(val) {
      if (this.isMounted) {
        this.borrowedPageSize = val;
        this.borrowedCurrentPage = 1;
      }
    },

    handleBorrowedCurrentChange(val) {
      if (this.isMounted) {
        this.borrowedCurrentPage = val;
      }
    },

    handleMyRecordsSizeChange(val) {
      if (this.isMounted) {
        this.myRecordsPageSize = val;
        this.myRecordsCurrentPage = 1;
      }
    },

    handleMyRecordsCurrentChange(val) {
      if (this.isMounted) {
        this.myRecordsCurrentPage = val;
      }
    },

    handleHistorySizeChange(val) {
      if (this.isMounted) {
        this.historyPageSize = val;
        this.historyCurrentPage = 1;
      }
    },

    handleHistoryCurrentChange(val) {
      if (this.isMounted) {
        this.historyCurrentPage = val;
      }
    },

    showBookDetail(book) {
      // 关键优化6：完善图书详情展示
      ElMessageBox.alert(
        `<div style="text-align: left;">
          <p><strong>图书名称：</strong>${book.bookName}</p>
          <p><strong>作者：</strong>${book.bookAuthor}</p>
          <p><strong>ISBN：</strong>${book.bookIsbn}</p>
          <p><strong>出版社：</strong>${book.bookPress || '未知'}</p>
          <p><strong>价格：</strong>¥${book.bookPrice}</p>
          <p><strong>页数：</strong>${book.bookPagination || '未知'}</p>
          <p><strong>上架时间：</strong>${this.formatDate(book.bookUploadtime)}</p>
          <p><strong>状态：</strong>${this.getStatusText(book.bookStatus)}</p>
        </div>`,
        '图书详情',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '关闭'
        }
      );
    },

    formatDate(dateString) {
      if (!dateString) return '-';
      try {
        return new Date(dateString).toLocaleDateString('zh-CN');
      } catch {
        return dateString;
      }
    },

    getStatusType(status) {
      const map = { '0': 'success', '1': 'warning', '2': 'info', '3': 'danger' };
      return map[status] || 'info';
    },

    getStatusText(status) {
      const map = { '0': '可借阅', '1': '已借阅', '2': '归还中', '3': '已下架' };
      return map[status] || '未知';
    },

    // 修复后：状态逻辑反转，与业务一致
    getMyRecordStatusType(status) {
      const map = { 
        '0': 'info',    // 已归还（蓝色标签）
        '1': 'warning', // 借阅中（黄色标签）
        '2': 'danger'   // 逾期（红色标签）
      };
      return map[status] || 'info';
    },
    getMyRecordStatusText(status) {
      const map = { 
        '0': '已归还', 
        '1': '借阅中', 
        '2': '逾期' 
      };
      return map[status] || '未知';
    },

    logout() {
      // 关键优化7：完善登出逻辑
      ElMessageBox.confirm(
        '确定要退出登录吗？',
        '登出确认',
        {
          confirmButtonText: '确认登出',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        localStorage.removeItem('userInfo');
        localStorage.removeItem('token');
        this.userInfo = {};
        this.isAdmin = false;
        this.avatarUrl = ''; // 登出时清空头像
        this.$router.push('/login');
        ElMessage.success('注销成功');
      }).catch(() => {
        ElMessage.info('已取消登出');
      });
    },

    handleSelectionChange(selection) {
      this.selectedBooks = selection;
      // 修复：当选中1条时赋值selectedBook，选中多条或取消选中时置空
      this.selectedBook = selection.length === 1 ? selection[0] : null;
      // 可选：打印日志，便于调试选中状态
      console.log('表格选中图书:', this.selectedBook);
    },

    // 管理员专属：显示新增对话框
    showAddBookDialog() {
      if (!this.isAdmin) {
        ElMessage.error('无权限发布新书');
        return;
      }
      this.resetBookForm();
      this.addBookDialogVisible = true;
    },

    // 管理员专属：显示编辑对话框
    showEditBookDialog(row) {
      if (!this.isAdmin) {
        ElMessage.error('无权限编辑图书');
        return;
      }

      // 修复1：优先使用行内按钮传入的row，无row则用表格选中的selectedBook
      let target = null;
      if (row) {
        // 行内编辑按钮：直接使用传入的图书数据
        target = row;
        // 同步更新selectedBook（确保后续保存时能获取到）
        this.selectedBook = target;
      } else {
        // 工具栏编辑按钮：使用表格选中的selectedBook
        target = this.selectedBook;
      }

      // 修复2：精准判断target是否存在（避免空值）
      if (!target || !target.bookId) {
        ElMessage.warning('请先选择要编辑的图书');
        return;
      }

      // 修复3：状态判断兼容数据类型（同时判断字符串和数字）
      const bookStatus = String(target.bookStatus); // 统一转为字符串
      if (bookStatus !== '0') {
        ElMessage.error('仅可编辑"可借阅"状态的图书');
        return;
      }

      // 修复4：深拷贝图书数据（避免修改表单时同步修改表格数据）
      this.bookForm = JSON.parse(JSON.stringify(target));
      this.editBookDialogVisible = true;
    },

    // 管理员专属：显示删除对话框
    showDeleteBookDialog(row) {
      if (!this.isAdmin) {
        ElMessage.error('无权限删除图书');
        return;
      }
      const target = row || this.selectedBook;
      if (!target) {
        ElMessage.warning('请先选择要删除的图书');
        return;
      }
      if (target.bookStatus !== '0') {
        ElMessage.error('仅可删除"可借阅"状态的图书');
        return;
      }
      this.selectedBook = target;
      this.deleteBookDialogVisible = true;
    },

    resetBookForm() {
      this.bookForm = {
        bookName: '',
        bookAuthor: '',
        bookIsbn: '',
        bookPress: '',
        bookPagination: '',
        bookPrice: '',
        bookImage: ''
      };
    },

    // 管理员专属：新增图书
    async handleAddBook() {
      if (!this.isAdmin) {
        ElMessage.error('无权限发布新书');
        this.addBookDialogVisible = false;
        return;
      }

      try {
        await this.$refs.addBookForm.validate();
        const bookData = {
          bookName: this.bookForm.bookName,
          bookAuthor: this.bookForm.bookAuthor,
          bookIsbn: this.bookForm.bookIsbn,
          bookPress: this.bookForm.bookPress || '',
          bookPagination: this.bookForm.bookPagination ? parseInt(this.bookForm.bookPagination) : null,
          bookPrice: this.bookForm.bookPrice ? parseFloat(this.bookForm.bookPrice) : null,
          bookImage: this.bookForm.bookImage || ''
        };
        const response = await addBook(bookData);
        
        // 精准适配后端：按code=0判断成功
        if (response.code === 0) {
          ElMessage.success(response.message || '新书发布成功');
          this.addBookDialogVisible = false;
          this.resetBookForm();
          this.loadAllBooks();
        } else {
          ElMessage.error(response.message || '发布失败');
        }
      } catch (error) {
        console.error('发布失败:', error);
        ElMessage.error('网络异常，发布失败');
      }
    },

    // 管理员专属：编辑图书
    // 管理员专属：编辑图书
    async handleEditBook() {
      if (!this.isAdmin) {
        ElMessage.error('无权限编辑图书');
        this.editBookDialogVisible = false;
        return;
      }

      // 修复：二次校验selectedBook和状态，双重保险
      if (!this.selectedBook || !this.selectedBook.bookId) {
        ElMessage.warning('请先选择要编辑的图书');
        this.editBookDialogVisible = false;
        return;
      }
      const bookStatus = String(this.selectedBook.bookStatus);
      if (bookStatus !== '0') {
        ElMessage.error('仅可编辑"可借阅"状态的图书');
        this.editBookDialogVisible = false;
        return;
      }

      try {
        await this.$refs.editBookForm.validate();
        const bookData = {
          bookId: this.selectedBook.bookId,
          bookName: this.bookForm.bookName,
          bookAuthor: this.bookForm.bookAuthor,
          bookIsbn: this.bookForm.bookIsbn,
          bookPress: this.bookForm.bookPress || '',
          bookPagination: this.bookForm.bookPagination ? parseInt(this.bookForm.bookPagination) : null,
          bookPrice: this.bookForm.bookPrice ? parseFloat(this.bookForm.bookPrice) : null
        };
        const response = await updateBook(bookData);
        if (response.code === 0) { // 简化判断：后端成功即提示，无需依赖data
          ElMessage.success('编辑成功');
          this.editBookDialogVisible = false;
          this.selectedBook = null;
          this.selectedBooks = [];
          this.$refs.bookTable?.clearSelection();
          this.loadAllBooks();
        } else {
          ElMessage.error('编辑失败：' + (response.message || '未知错误'));
        }
      } catch (error) {
        console.error('编辑失败:', error);
        ElMessage.error('编辑失败');
      }
    },

    // 管理员专属：删除图书
    async handleDeleteBook() {
      if (!this.isAdmin) {
        ElMessage.error('无权限删除图书');
        this.deleteBookDialogVisible = false;
        return;
      }
      if (!this.selectedBook) {
        ElMessage.warning('请先选择要删除的图书');
        return;
      }
      if (this.selectedBook.bookStatus !== '0') {
        ElMessage.error('仅可删除"可借阅"状态的图书');
        this.deleteBookDialogVisible = false;
        return;
      }

      try {
        const response = await deleteBook(this.selectedBook.bookId);
        
        // 精准适配后端：按code=0判断成功
        if (response.code === 0) {
          ElMessage.success(response.message || '删除成功');
          this.deleteBookDialogVisible = false;
          this.selectedBook = null;
          this.selectedBooks = [];
          this.$refs.bookTable?.clearSelection();
          this.loadAllBooks();
        } else {
          ElMessage.error(response.message || '删除失败');
        }
      } catch (error) {
        console.error('删除失败:', error);
        ElMessage.error('网络异常，删除失败');
      }
    },

    getBookImage(book) {
      if (!book.bookImage) return null;
      if (book.bookImage.startsWith('data:image/') || book.bookImage.startsWith('http')) {
        return book.bookImage.includes('covers.openlibrary.org') ? null : book.bookImage;
      }
      return null;
    },

    handleImageError(event) {
      const img = event.target;
      const isbn = img.dataset.isbn;
      if (!isbn || img.dataset.triedSources) {
        img.style.display = 'none';
        const placeholder = img.parentElement.querySelector('.book-cover-placeholder');
        if (placeholder) {
          placeholder.style.display = 'flex';
        }
        return;
      }

      img.dataset.triedSources = '1';
      const fallbacks = [
        `https://img1.doubanio.com/view/subject/s/public/s${isbn}.jpg`,
        `https://img2.doubanio.com/view/subject/s/public/s${isbn}.jpg`,
        `https://img9.doubanio.com/view/subject/s/public/s${isbn}.jpg`
      ];
      const currentIdx = fallbacks.findIndex(src => img.src.includes(src.split('/').pop()));
      if (currentIdx < fallbacks.length - 1) {
        img.src = fallbacks[currentIdx + 1];
      } else {
        img.style.display = 'none';
        const placeholder = img.parentElement.querySelector('.book-cover-placeholder');
        if (placeholder) {
          placeholder.style.display = 'flex';
        }
      }
    },

    getBookIcon(book) {
      const title = book.bookName.toLowerCase();
      const author = book.bookAuthor.toLowerCase();
      if (title.includes('java') || title.includes('编程')) return '💻';
      if (title.includes('小说') || title.includes('文学')) return '📖';
      if (title.includes('历史') || title.includes('传记')) return '📜';
      if (title.includes('科学') || title.includes('技术')) return '🔬';
      if (title.includes('艺术') || title.includes('设计')) return '🎨';
      if (title.includes('哲学') || title.includes('思想')) return '🤔';
      if (title.includes('经济') || title.includes('管理')) return '💰';
      if (title.includes('教育') || title.includes('学习')) return '🎓';
      return '📚';
    },

    getBookCategory(book) {
      const title = book.bookName.toLowerCase();
      const author = book.bookAuthor.toLowerCase();
      if (title.includes('java') || title.includes('编程')) return '技术编程';
      if (title.includes('小说') || title.includes('文学')) return '文学小说';
      if (title.includes('历史') || title.includes('传记')) return '历史传记';
      if (title.includes('科学') || title.includes('技术')) return '科学技术';
      if (title.includes('艺术') || title.includes('设计')) return '艺术设计';
      if (title.includes('哲学') || title.includes('思想')) return '哲学思想';
      if (title.includes('经济') || title.includes('管理')) return '经济管理';
      if (title.includes('教育') || title.includes('学习')) return '教育学习';
      return '综合图书';
    },

    handleImageUpload(file) {
      const actualFile = file.raw || file;
      if (!actualFile.type.startsWith('image/')) {
        ElMessage.error('仅支持图片文件');
        return false;
      }
      if (actualFile.size / 1024 / 1024 >= 2) {
        ElMessage.error('图片大小不能超过2MB');
        return false;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        this.bookForm.bookImage = e.target.result;
        ElMessage.success('图片上传成功');
      };
      reader.onerror = () => ElMessage.error('图片读取失败');
      reader.readAsDataURL(actualFile);
      return false;
    },

    removeImage() {
      this.bookForm.bookImage = '';
      ElMessage.success('图片已删除');
    },

    // 管理员专属：加载用户统计
    async loadUserStats() {
      // 前置拦截：非管理员直接返回空统计，不发起接口请求
      if (!this.isAdmin) {
        this.userStats = { totalUsers: 0, adminUsers: 0, normalUsers: 0 };
        return;
      }

      try {
        const response = await getAllUsers();
        // 仅当响应成功且有数据时，更新统计
        if (response.code === 0 && Array.isArray(response.data)) {
          const users = response.data;
          this.userStats = {
            totalUsers: users.length,
            adminUsers: users.filter(u => u.userRole.toUpperCase() === 'ADMIN').length,
            normalUsers: users.filter(u => u.userRole.toUpperCase() === 'USER').length
          };
        } else {
          // 接口响应异常时的降级处理
          this.userStats = { totalUsers: 0, adminUsers: 0, normalUsers: 0 };
          ElMessage.warning('用户统计数据加载异常');
        }
      } catch (error) {
        console.error('获取用户统计失败:', error);
        // 区分无权限和其他错误，给出精准提示
        const errorMsg = error.response?.data?.message || '获取用户统计失败';
        ElMessage.error(errorMsg);
        this.userStats = { totalUsers: 0, adminUsers: 0, normalUsers: 0 };
      }
    },
    goToUserCenter() {
      if (!this.isAdmin) {
        ElMessage.error('无权限访问用户中心');
        return;
      }
      this.$router.push('/user-center');
    },

    async refreshUserData() {
      if (!this.isAdmin) {
        ElMessage.error('无权限刷新用户数据');
        return;
      }
      await this.loadUserStats();
      ElMessage.success('用户数据刷新成功');
    }
  }
}
</script>

<style scoped>
.home {
  min-height: 100vh;
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  background-attachment: fixed;
  /* overflow: hidden; */
}

* {
  scrollbar-width: none;
  -ms-overflow-style: none;
}

*::-webkit-scrollbar {
  display: none;
}
/* 
body {
  overflow: hidden !important;
} */

.nav-menu {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.nav-search {
  position: absolute;
  right: 200px;
  top: 50%;
  transform: translateY(-50%);
}

.nav-search-input {
  width: 280px;
}

.nav-search-input .el-input__wrapper {
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(168, 237, 234, 0.4);
  border-radius: 25px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.nav-search-input .el-input__wrapper:hover {
  border-color: #a8edea;
  box-shadow: 0 4px 15px rgba(168, 237, 234, 0.3);
}

.nav-search-input .el-input__wrapper.is-focus {
  border-color: #a8edea;
  box-shadow: 0 4px 15px rgba(168, 237, 234, 0.4);
}

.nav-search-input .el-button .el-icon {
  background: linear-gradient(135deg, #a8edea, #fed6e3);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transition: all 0.3s ease;
}

.nav-search-input .el-button:hover .el-icon {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transform: scale(1.1);
}

.search-prefix-icon {
  background: linear-gradient(135deg, #a8edea, #fed6e3);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transition: all 0.3s ease;
  font-size: 16px;
}

.nav-search-input .el-input__wrapper:hover .search-prefix-icon {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transform: scale(1.1);
}

.nav-search-input .el-input__wrapper.is-focus .search-prefix-icon {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transform: scale(1.1);
}

.user-menu {
  position: absolute;
  right: 30px;
  top: 50%;
  transform: translateY(-50%);
}

.el-dropdown-link {
  color: #2c3e50;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 16px;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
  border: 1px solid rgba(102, 126, 234, 0.2);
}

.el-dropdown-link:hover {
  background: rgba(102, 126, 234, 0.1);
  border-color: #667eea;
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.2);
}

.el-dropdown-link .el-icon {
  font-size: 16px;
  background: linear-gradient(135deg, #a8edea, #fed6e3);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transition: all 0.3s ease;
}

.el-dropdown-link:hover .el-icon {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transform: scale(1.1);
}

.nav-menu .el-menu-item .el-icon {
  margin-right: 8px;
  font-size: 18px;
  background: linear-gradient(135deg, #a8edea, #fed6e3);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transition: all 0.3s ease;
}

.nav-menu .el-menu-item:hover .el-icon {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transform: scale(1.1);
}

.nav-menu .el-menu-item:hover {
  background-color: #e8e8e8 !important;
}

.nav-menu .el-menu-item.is-active {
  background-color: transparent !important;
}

.nav-menu .el-menu-item.is-active .el-icon {
  background: linear-gradient(135deg, #d299c2, #fef9d7);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}


.content-container {
  padding: 20px;
  margin-top: 20px;
}

.content-container.carousel-mode {
  height: calc(100vh - 60px);
  padding: 0;
  margin-top: 60px;
  overflow: hidden;
  background: transparent;
}

.carousel-section {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  margin: 0;
  background: transparent;
  box-shadow: none;
  border-radius: 0;
}

.section {
  background: rgba(255, 255, 255, 0.95);
  padding: 30px;
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  margin-bottom: 20px;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px 0;
  position: relative;
  overflow: hidden;
}

.section-title::before {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  border-radius: 2px;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.section-title::after {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(102, 126, 234, 0.1), transparent);
  animation: shimmer 3s infinite;
}

@keyframes shimmer {
  0% { left: -100%; }
  100% { left: 100%; }
}

.section-title .el-icon {
  font-size: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin-right: 20px;
  padding: 8px;
  border-radius: 12px;
  background-color: rgba(102, 126, 234, 0.1);
  transition: all 0.3s ease;
  position: relative;
  z-index: 2;
}

.section-title .el-icon::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  border-radius: 12px;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: -1;
}

.section-title:hover .el-icon::before {
  opacity: 0.1;
}

.section-title h2 {
  margin: 0;
  background: linear-gradient(135deg, #2c3e50 0%, #667eea 50%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  font-size: 32px;
  font-weight: 800;
  letter-spacing: 1px;
  position: relative;
  z-index: 2;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.search-box {
  display: flex;
  align-items: center;
}

.sort-select {
  margin-right: 8px;
}

.admin-box {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-results {
  margin: 20px 0;
}

.search-results h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 18px;
}

.book-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.book-card {
  display: flex;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.book-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.book-image {
  width: 150px;
  height: 200px;
  flex-shrink: 0;
}

.book-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.book-cover-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #ff6b6b 0%, #4ecdc4 50%, #45b7d1 100%);
  border: 2px solid #fff;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  text-align: center;
  position: relative;
  overflow: hidden;
  box-shadow: 0 6px 20px rgba(0,0,0,0.15);
}

.book-cover-placeholder::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
  animation: shimmer 3s ease-in-out infinite;
}

.book-cover-icon {
  font-size: 3em;
  margin-bottom: 8px;
  z-index: 2;
  position: relative;
  filter: drop-shadow(0 2px 4px rgba(0,0,0,0.3));
}

.book-cover-title {
  font-size: 1.1em;
  font-weight: bold;
  margin-bottom: 4px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.4);
  z-index: 2;
  position: relative;
  padding: 0 8px;
  line-height: 1.3;
  max-height: 2.6em;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.book-cover-author {
  font-size: 0.8em;
  opacity: 0.95;
  text-shadow: 0 1px 3px rgba(0,0,0,0.4);
  z-index: 2;
  position: relative;
  margin-bottom: 8px;
  max-width: 90%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.book-cover-category {
  font-size: 0.7em;
  opacity: 0.8;
  background: rgba(255,255,255,0.2);
  padding: 2px 8px;
  border-radius: 12px;
  z-index: 2;
  position: relative;
  backdrop-filter: blur(10px);
}

.book-info {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.book-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0 0 10px 0;
  line-height: 1.4;
}

.book-author,
.book-isbn,
.book-press,
.book-price {
  margin: 5px 0;
  color: #666;
  font-size: 14px;
}

.book-status {
  margin: 10px 0;
}

.book-actions {
  margin-top: 15px;
}

.book-actions .el-button {
  width: 100%;
}

.book-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.book-uploader:hover {
  border-color: #409eff;
}

.book-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
  display: block;
}

.book-image-preview {
  width: 150px;
  height: 150px;
  object-fit: cover;
  display: block;
}

.upload-tip {
  margin-top: 8px;
  text-align: center;
}

.upload-tip p {
  margin: 2px 0;
  font-size: 12px;
  color: #999;
}

.image-actions {
  margin-top: 8px;
  text-align: center;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.history-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409EFF;
}

.history-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.book-name {
  font-weight: 500;
  color: #333;
}

.book-isbn {
  font-family: 'Courier New', monospace;
  color: #666;
}

.el-tag {
  font-size: 12px;
}

.user-center-content {
  padding: 20px 0;
}

.user-center-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin: 30px 0;
}

.user-stats {
  margin-top: 30px;
}

.stat-card {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  color: white;
  font-size: 24px;
}

.stat-icon.admin {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
}

.stat-icon.normal {
  background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
  font-weight: 500;
}

/* 新增：圆形头像样式 */
.avatar-container {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid rgba(168, 237, 234, 0.5);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  margin-right: 8px;
}

.avatar-container:hover {
  border-color: #a8edea;
  box-shadow: 0 4px 12px rgba(168, 237, 234, 0.3);
  transform: scale(1.05);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

@media (max-width: 1200px) {
  .nav-search {
    right: 180px;
  }

  .nav-search-input {
    width: 250px;
  }
}

@media (max-width: 992px) {
  .nav-search {
    right: 160px;
  }

  .nav-search-input {
    width: 220px;
  }

  .user-menu {
    right: 20px;
  }
}

@media (max-width: 768px) {
  .nav-search {
    position: static;
    transform: none;
    margin: 10px 20px;
    width: calc(100% - 40px);
  }

  .nav-search-input {
    width: 100%;
  }

  .user-menu {
    position: static;
    transform: none;
    margin: 10px 20px;
    text-align: center;
  }

  .nav-menu {
    flex-direction: column;
    height: auto;
  }

  .nav-menu .el-menu-item {
    width: 100%;
    text-align: center;
  }
}
</style>
